package yelmor.comm100.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import yelmor.comm100.domain.CoUser;
import yelmor.comm100.repository.CoUserRepository;
import yelmor.comm100.util.SecurityUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by yel on 2016/5/7.
 */
@Controller
public class FileuploadController {


  @Autowired
  private CoUserRepository coUserRepository;

  @Value("${sideImageDir}")
  private String sideImageDir;

  @Value("${logoImageDir}")
  private String logoImageDir;

  @RequestMapping(value = "/sideImageUpload", method = RequestMethod.POST)
  public String handleFileUploadGet(@RequestParam("file") MultipartFile file) {
    System.out.println("file: " + file.getName());
    String curUserName = SecurityUtil.getCurrentUserName();
    if(curUserName.equals("anonymousUser")) {
    } else {
      CoUser coUser = coUserRepository.findOne(curUserName);
      System.out.println("file: " + sideImageDir);
      if (!file.isEmpty()) {
        try {
          BufferedOutputStream stream = new BufferedOutputStream(
                  new FileOutputStream(new File(sideImageDir + coUser.getSiteCode())));
          FileCopyUtils.copy(file.getInputStream(), stream);
          stream.close();
        } catch (Exception e) {
        }
      } else {
      }
    }

    return "redirect:/user/imgConfig";
  }
  @RequestMapping(value = "/logoImageUpload", method = RequestMethod.POST)
  public String logoImageUpload(@RequestParam("file") MultipartFile file) {
    System.out.println("file: " + file.getName());
    String curUserName = SecurityUtil.getCurrentUserName();
    if(curUserName.equals("anonymousUser")) {
    } else {
      CoUser coUser = coUserRepository.findOne(curUserName);
      System.out.println("file: " + logoImageDir);
      if (!file.isEmpty()) {
        try {
          BufferedOutputStream stream = new BufferedOutputStream(
                  new FileOutputStream(new File(logoImageDir + coUser.getSiteCode())));
          FileCopyUtils.copy(file.getInputStream(), stream);
          stream.close();
        } catch (Exception e) {
        }
      } else {
      }
    }

    return "redirect:/user/imgConfig";
  }

  @RequestMapping(method = RequestMethod.GET, value = "/ffff")
  public String provideUploadInfo(Model model) {
    File rootFolder = new File("tmp");
    List<String> fileNames = Arrays.stream(rootFolder.listFiles())
            .map(f -> f.getName())
            .collect(Collectors.toList());

    model.addAttribute("files",
            Arrays.stream(rootFolder.listFiles())
                    .sorted(Comparator.comparingLong(f -> -1 * f.lastModified()))
                    .map(f -> f.getName())
                    .collect(Collectors.toList())
    );

    return "uploadForm";
  }

  @RequestMapping(method = RequestMethod.POST, value = "/ffff")
  public String handleFileUpload(@RequestParam("name") String name,
                                 @RequestParam("file") MultipartFile file,
                                 RedirectAttributes redirectAttributes) {
    if (name.contains("/")) {
      redirectAttributes.addFlashAttribute("message", "Folder separators not allowed");
      return "redirect:/";
    }
    if (name.contains("/")) {
      redirectAttributes.addFlashAttribute("message", "Relative pathnames not allowed");
      return "redirect:/";
    }

    if (!file.isEmpty()) {
      try {
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File("tmp" + "/" + name)));
        FileCopyUtils.copy(file.getInputStream(), stream);
        stream.close();
        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded " + name + "!");
      }
      catch (Exception e) {
        redirectAttributes.addFlashAttribute("message",
                "You failed to upload " + name + " => " + e.getMessage());
      }
    }
    else {
      redirectAttributes.addFlashAttribute("message",
              "You failed to upload " + name + " because the file was empty");
    }

    return "redirect:/";
  }

}
